import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import config from '../config/index.js';
import { BusinessError } from './errorHandler.js';
import { processAvatarImage } from '../utils/imageProcessor.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 确保上传目录存在
const ensureUploadDir = (dir) => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
};

// 生成唯一文件名
const generateFileName = (originalname) => {
  const timestamp = Date.now();
  const random = Math.random().toString(36).substring(2, 8);
  const ext = path.extname(originalname);
  return `${timestamp}_${random}${ext}`;
};

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 检查文件类型
  if (config.upload.allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new BusinessError('不支持的文件类型'), false);
  }
};

// 存储配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadPath = path.resolve(config.upload.path);
    ensureUploadDir(uploadPath);
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    const fileName = generateFileName(file.originalname);
    cb(null, fileName);
  }
});

// 基础上传配置
const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: config.upload.maxSize,
    files: 10 // 最多10个文件
  }
});

// 单文件上传中间件
export const uploadSingle = (fieldName = 'file') => {
  return (req, res, next) => {
    const uploadMiddleware = upload.single(fieldName);
    
    uploadMiddleware(req, res, (err) => {
      if (err) {
        if (err instanceof multer.MulterError) {
          if (err.code === 'LIMIT_FILE_SIZE') {
            return next(new BusinessError('文件大小超出限制'));
          }
          if (err.code === 'LIMIT_UNEXPECTED_FILE') {
            return next(new BusinessError('不支持的文件字段'));
          }
        }
        return next(err);
      }
      
      // 添加文件URL到请求对象
      if (req.file) {
        req.file.url = `/uploads/${req.file.filename}`;
      }
      
      next();
    });
  };
};

// 多文件上传中间件
export const uploadMultiple = (fieldName = 'files', maxCount = 5) => {
  return (req, res, next) => {
    const uploadMiddleware = upload.array(fieldName, maxCount);
    
    uploadMiddleware(req, res, (err) => {
      if (err) {
        if (err instanceof multer.MulterError) {
          if (err.code === 'LIMIT_FILE_SIZE') {
            return next(new BusinessError('文件大小超出限制'));
          }
          if (err.code === 'LIMIT_UNEXPECTED_FILE') {
            return next(new BusinessError('文件数量超出限制'));
          }
        }
        return next(err);
      }
      
      // 添加文件URL到请求对象
      if (req.files && req.files.length > 0) {
        req.files = req.files.map(file => ({
          ...file,
          url: `/uploads/${file.filename}`
        }));
      }
      
      next();
    });
  };
};

// 多字段文件上传中间件
export const uploadFields = (fields) => {
  return (req, res, next) => {
    const uploadMiddleware = upload.fields(fields);
    
    uploadMiddleware(req, res, (err) => {
      if (err) {
        if (err instanceof multer.MulterError) {
          if (err.code === 'LIMIT_FILE_SIZE') {
            return next(new BusinessError('文件大小超出限制'));
          }
          if (err.code === 'LIMIT_UNEXPECTED_FILE') {
            return next(new BusinessError('不支持的文件字段'));
          }
        }
        return next(err);
      }
      
      // 添加文件URL到请求对象
      if (req.files) {
        Object.keys(req.files).forEach(fieldName => {
          req.files[fieldName] = req.files[fieldName].map(file => ({
            ...file,
            url: `/uploads/${file.filename}`
          }));
        });
      }
      
      next();
    });
  };
};

// 删除文件工具函数
export const deleteFile = (filename) => {
  try {
    const filePath = path.join(config.upload.path, filename);
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
      return true;
    }
    return false;
  } catch (error) {
    console.error('删除文件失败:', error);
    return false;
  }
};

// 删除多个文件
export const deleteFiles = (filenames) => {
  const results = [];
  filenames.forEach(filename => {
    results.push(deleteFile(filename));
  });
  return results;
};

// 获取文件信息
export const getFileInfo = (filename) => {
  try {
    const filePath = path.join(config.upload.path, filename);
    if (fs.existsSync(filePath)) {
      const stats = fs.statSync(filePath);
      return {
        filename,
        size: stats.size,
        created: stats.birthtime,
        modified: stats.mtime,
        url: `/uploads/${filename}`
      };
    }
    return null;
  } catch (error) {
    console.error('获取文件信息失败:', error);
    return null;
  }
};

// 验证图片文件
export const validateImageFile = (file) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  return allowedTypes.includes(file.mimetype);
};

// 专家头像上传中间件（带图片处理）
export const uploadAvatar = (req, res, next) => {
  const uploadMiddleware = uploadSingle('avatar');

  uploadMiddleware(req, res, async (err) => {
    if (err) {
      return next(err);
    }

    // 如果没有上传文件，直接继续
    if (!req.file) {
      return next();
    }

    try {
      // 处理头像图片（缩放）
      const filePath = req.file.path;
      const processResult = await processAvatarImage(filePath);

      // 将处理结果添加到请求对象中，供后续使用
      req.file.imageProcessed = processResult.processed;
      if (processResult.originalSize) {
        req.file.originalSize = processResult.originalSize;
      }
      if (processResult.newSize) {
        req.file.newSize = processResult.newSize;
      }

      console.log('头像图片处理完成:', {
        filename: req.file.filename,
        processed: processResult.processed,
        originalSize: processResult.originalSize,
        newSize: processResult.newSize
      });

      next();
    } catch (error) {
      console.error('头像图片处理失败:', error);

      // 图片处理失败时，删除已上传的文件
      if (req.file && req.file.path && fs.existsSync(req.file.path)) {
        try {
          fs.unlinkSync(req.file.path);
        } catch (deleteError) {
          console.error('删除失败的上传文件时出错:', deleteError);
        }
      }

      // 返回用户友好的错误信息
      const errorMessage = error.message || '图片处理失败';
      next(new BusinessError(`头像上传失败: ${errorMessage}`));
    }
  });
};

// 专家展示图片上传中间件
export const uploadDisplayImages = uploadMultiple('display_images', 5);

export default {
  uploadSingle,
  uploadMultiple,
  uploadFields,
  uploadAvatar,
  uploadDisplayImages,
  deleteFile,
  deleteFiles,
  getFileInfo,
  validateImageFile
};
